package cn.iocoder.yudao.module.exam.service.questionbank;

import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import cn.iocoder.yudao.module.exam.controller.admin.questionbank.vo.*;
import cn.iocoder.yudao.module.exam.dal.dataobject.questionbank.QuestionBankDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.PageParam;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.exam.dal.mysql.questionbank.QuestionBankMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.exam.enums.ErrorCodeConstants.*;

/**
 * 试题题库题目关联 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class QuestionBankServiceImpl implements QuestionBankService {

    @Resource
    private QuestionBankMapper questionBankMapper;

    @Override
    public Long createQuestionBank(QuestionBankSaveReqVO createReqVO) {
        // 插入
        QuestionBankDO questionBank = BeanUtils.toBean(createReqVO, QuestionBankDO.class);
        questionBankMapper.insert(questionBank);
        // 返回
        return questionBank.getId();
    }

    @Override
    public void updateQuestionBank(QuestionBankSaveReqVO updateReqVO) {
        // 校验存在
        validateQuestionBankExists(updateReqVO.getId());
        // 更新
        QuestionBankDO updateObj = BeanUtils.toBean(updateReqVO, QuestionBankDO.class);
        questionBankMapper.updateById(updateObj);
    }

    @Override
    public void deleteQuestionBank(Long id) {
        // 校验存在
        validateQuestionBankExists(id);
        // 删除
        questionBankMapper.deleteById(id);
    }

    private void validateQuestionBankExists(Long id) {
        if (questionBankMapper.selectById(id) == null) {
            throw exception(QUESTION_BANK_NOT_EXISTS);
        }
    }

    @Override
    public QuestionBankDO getQuestionBank(Long id) {
        return questionBankMapper.selectById(id);
    }

    @Override
    public PageResult<QuestionBankDO> getQuestionBankPage(QuestionBankPageReqVO pageReqVO) {
        return questionBankMapper.selectPage(pageReqVO);
    }

}